package com.bbcare.encrypt;

import java.util.Map;

import com.bbcare.encrypt.algorithm.EncryptAlgorithm;
import com.bbcare.encrypt.factory.EncryPtFactory;

public class Encrypt {


	public static Object encode(Object plaintextEntity, String encryptType)
			throws Exception {
		EncryptAlgorithm encryptAlgorithm = EncryPtFactory
				.getInstance(encryptType);

		if (plaintextEntity != null) {
			if (plaintextEntity instanceof Map) {
				Map<String, Object> map = EncryptUtil.typeCast(plaintextEntity);
				encryptAlgorithm.encodeMap(map);
				return map;
			} else if (plaintextEntity instanceof String) {
				return encryptAlgorithm.encode(plaintextEntity.toString());
			}
		}
		return null;
	}

	public static Object decode(Object ciphertextEntity)
			throws Exception {
		if (ciphertextEntity != null) {
			if (ciphertextEntity instanceof Map) {
				EncryptAlgorithm encryptAlgorithm = null;
				
				Map<String, Object> map = EncryptUtil.typeCast(ciphertextEntity);
				int i=0;
				for(String key : map.keySet()){
					String ciphertext = (String) map.get(key);
					if(i == 0){
						encryptAlgorithm = EncryPtFactory.getInstance(EncryptUtil.dealWith(ciphertext, null));
					}
					break;
				}
				
				encryptAlgorithm.decodeMap(map);
				return map;
			} else if (ciphertextEntity instanceof String) {
				String ciphertext = ciphertextEntity.toString();
				String encryptType = EncryptUtil.dealWith(ciphertext, null);
				EncryptAlgorithm encryptAlgorithm = EncryPtFactory
						.getInstance(encryptType);
				ciphertext = ciphertext.substring(0, ciphertext.toString()
						.length() - 3);
				return encryptAlgorithm.decode(ciphertext);
			}
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		String name = "A0F29AEB5A01135564E3B5EA804EC4AE001";
		System.out.println(decode(name));
	}
	
}
